<?php

namespace app\service;

require_once EXTEND_PATH . '/Baidu/AipSpeech.php';
/*
 * 语音转文字（百度SDK）
 *
 */
class BaiduApi
{
	public function app()
	{
		$APP_ID = getenv('BAIDU_AUDIO_APP_ID');
		$API_KEY = getenv('BAIDU_AUDIO_APP_KEY');
		$SECRET_KEY = getenv('BAIDU_AUDIO_SECRET_KEY');
		$client = new \AipSpeech($APP_ID, $API_KEY, $SECRET_KEY);
		return $client;
	}

	public static function Asr($audio = '')
	{
        // $audio = 'C:\Users\Administrator\Downloads\00644e444d8603a6bcc7931f4b672adf.mp3';
        $filepath = explode('/', $audio);
        $filepath = explode('.', $filepath[sizeof($filepath) - 1]);

        $filename = $filepath[0];
        if($cache = cache('baidu:asr:'.$filename)){
        	return $cache;
        }
        $tempDir = ROOT_PATH . 'runtime' . DS . 'audio';
        if (!file_exists($tempDir)) {
            // 检查目录是否存在，如果不存在则创建
            if (mkdir($tempDir, 0777, true)) {
            } else {
                return false;
            }
        }
        $savepath = $tempDir . DS . $filename . '.wav';
        $audio = FFmpegService::FormatWav($audio, $savepath);
        if(!$audio){
            return false;
        }
        try {
	        $file = file_get_contents($audio);
			$app = (new BaiduApi)->app();
			$result = $app->asr($file, 'wav', 8000, array(
			    'dev_pid' => 1537,
			));
			unlink($savepath);
        } catch (\Exception $e) {
			return false;
        }
		if($result['err_no'] == 0){
			$result = implode('', $result['result']);
			cache('baidu:asr:' . $filename, $result, 600);
			return $result;
		}else{
			return false;
		}
	}


    public static function getAccessToken(){
    	$cachekey = 'baiduapitoken';
    	$cacheToken = cache($cachekey);
    	if ($cacheToken) return $cacheToken;
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => getenv('BAIDU_AUDIO_APP_KEY'),
            'client_secret' => getenv('BAIDU_AUDIO_SECRET_KEY')
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        if ($rtn->expires_in && $rtn->access_token) {
        	cache($cachekey, $rtn->access_token, $rtn->expires_in);
        }
        return $rtn->access_token;
    }
	public static function idcardOCR($path='', $side = 'front')
	{
		$url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" . self::getAccessToken();
		$img = file_get_contents($path);
		$img = base64_encode($img);
		$bodys = array(
		    'id_card_side' => $side,
		    'image' => $img,
		    'AESEncry'=>'false'
		);
		$res = sendcurl($url, json_encode($bodys));

		if ($res['code'] != 200) return false;

		$result = $res['data'];
		$result = json_decode($result, true);
		if ($result['image_status'] != 'normal') return false;
		$return = [];
		foreach ($result['words_result'] as $key => $value) {
			if ($key == '姓名') {
				$return['name'] = $value['words'];
				continue;
			}
			if ($key == '公民身份号码') {
				$return['number'] = $value['words'];
				continue;
			}
			if ($key == '出生') {
				$return['birthday'] = $value['words'];
				continue;
			}
			if ($key == '民族') {
				$return['nation'] = $value['words'];
				continue;
			}
			if ($key == '住址') {
				$return['address'] = $value['words'];
				continue;
			}
			if ($key == '性别') {
				$return['sex'] = $value['words'];
				continue;
			}
		}

		return $return;
	}

	public static function GetKeyword($title = '', $content = '')
	{
		$token = self::getAccessToken();
		$url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/keyword?access_token=".$token;

		$bodys = array(
		    'title' => $title,
		    'content' => $content,
		);
		$res = http_post($url, $bodys);
		if (!$res) {
			return false;
		}
		if (isset($res['error_code'])) {
			return false;
		}
		// return $res;
		return array_column($res['items'], 'tag');
	}


	public static function GetCategory($title = '', $content = '')
	{
		$token = self::getAccessToken();
		$url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/topic?charset=UTF-8&access_token=".$token;

		$bodys = array(
		    'title' => $title,
		    'content' => $content,
		);
		$res = http_post($url, $bodys);
		if (!$res) {
			return false;
		}
		if (isset($res['error_code'])) {
			return false;
		}
		return $res['item']['lv1_tag_list'][0]['tag'];
	}

	// https://cloud.baidu.com/doc/OCR/s/9k3h7xuv6
	public static function imageOCR($path='')
	{
		$url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" . self::getAccessToken();
		$img = file_get_contents($path);
		$img = base64_encode($img);
		$bodys = array(
		    'image' => $img
		);
		$res = sendcurl($url, json_encode($bodys));

		if ($res['code'] != 200) return false;

		$result = $res['data'];
		$result = json_decode($result, true);
		if (!$result['words_result_num']) return [];
		$return = [];
		foreach ($result['words_result'] as $key => $value) {
			$return[] = $value['words'];
		}

		return $return;
	}
}